<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>热部署演示</title>
    <style type="text/css">
        #id_canvas_scene {
          border: 1px solid #ccc;
        }
        .canvasBox {
          width: 600px;
          margin: 0 auto;
          text-align: center;
        }
      </style>
</head>

<body>
<div class="canvasBox">
    <canvas id="id_canvas_scene" height="400" width="400"></canvas>
</div>
<script type="text/javascript">
    var canvas = document.getElementById('id_canvas_scene')
    var ctx = canvas.getContext('2d')

    var lineColor = "#0"
    var rows = 1, cols = 1, lineWidth = 1
    var gridWidth = canvas.width / cols, gridHeight = canvas.height / rows
    var ws = null
    var host = 'ws://localhost:10500'
    var userid = (1000000000 + Math.ceil((Math.random() * 2000000000))) + ""
    var roles = {}
    var mouseDown = false
    var roleAlpha = 0.7
    var color = "#"
    color = color + Math.max(Math.ceil(Math.random() * 0x7), 0x0)
    color = color + Math.max(Math.ceil(Math.random() * 0x7), 0x0)
    color = color + Math.max(Math.ceil(Math.random() * 0x7), 0x0)
    console.log(userid, color)
    
    var sendData = function(data) {
        console.log("send", data)
        ws.send(JSON.stringify(data))
    }
    
    function drawLine(x1, y1, x2, y2) {
        ctx.strokeStyle = lineColor
        ctx.lineWidth = lineWidth
        ctx.globalAlpha = 1.0
        ctx.lineCap = "butt"
        ctx.lineJoin = "miter"
        ctx.moveTo(x1, y1)
        ctx.lineTo(x2, y2)
        ctx.stroke()
        
    }
    var refreshScene = function() {
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.beginPath()
        // 画格子
        for (var i = 0; i <= rows; i++) {
            drawLine(0, i * gridWidth, canvas.width, i * gridWidth)
        }
        for (var i = 0; i <= cols; i++) {
            drawLine(i * gridHeight, 0, i * gridHeight, canvas.height)
        }
        // 画角色
        ctx.globalAlpha = roleAlpha
        for (var key in roles) {
            var role = roles[key]
            if (!role || role == null) {
                continue
            }
            var pos = role.pos
            ctx.fillStyle = role.color
            ctx.fillRect(pos.x * gridWidth, pos.y * gridHeight, gridWidth, gridHeight)
            ctx.fill()
        }
        ctx.closePath()
    }

    function initGame(data) {
        rows = data.rows
        cols = data.cols
        gridWidth = canvas.width / cols
        gridHeight = canvas.height / rows

        refreshScene()
    }

    function sendLocalRole() {
        sendData({action:"roleenter", params: {userid:userid, color: color, pos: {x: 0, y: 0}}})
    }

    function createRole(data) {
        console.log("data", data)
        var role = {
            userid: data.userid,
            pos: data.pos,
            color: data.color
        }
        role.move = function(vec2) {
            role.pos.x = role.pos.x + vec2.x
            role.pos.y = role.pos.y + vec2.y
            if (role.pos.x >= cols) {
                role.pos.x = 0
            }
            if (role.pos.y >= rows) {
                role.pos.y = 0
            }
        }
        role.moveto = function(pos) {
            role.pos = pos
        }

        roles[role.userid] = role
    }
    
    function parser(data) {
        if (data.action == "move") {
            roles[data.params.userid].move(data.params.vec2)
        }
        else if (data.action == "moveto") {
            roles[data.params.userid].moveto(data.params.pos)
        }
        else if (data.action == "roleenter") {
            createRole(data.params)
        }
        else if (data.action == "roleleave") {
            roles[data.params.userid] = null
        }
        else if (data.action == "initgame") {
            initGame(data.params)
        }

        refreshScene()
    }    

    function initSession() {
        if (ws) {
            ws.close()
        }

        ws = new WebSocket(host + "?userid=" + userid);
        ws.onopen = () => {
            sendLocalRole()
        }

        ws.onmessage = (event) => {
            var msg = event.data
            console.log("recv raw: " + msg)
            parser(JSON.parse(msg))
        }

        ws.onerror = (error) => {
            if (error) {
                console.log(error)
            }

            // 等待3秒去重连
            initSession()
        }

        ws.onclose = () => {

        }
    }

    function registerMouse() {
        canvas.onmousedown = function (e) {
            mouseDown = true
        }
        canvas.onmousemove = function (e) {
        }
 
        canvas.onmouseup = function (e) {
            var x = Math.floor(e.layerX / gridWidth)
            var y = Math.floor(e.layerY / gridHeight)

            var role = roles[userid]
            var pos = role.pos
            var vec2 = {x: x - pos.x, y: y - pos.y}
            // console.log(e.clientX, e.clientY, x, y, pos, vec2)
            vec2.x = Math.sign(vec2.x)
            vec2.y = Math.sign(vec2.y)

            sendData({action: "move", params: {userid: userid, vec2: vec2}})
        }
 
        canvas.mouseleave = function (e) {
        }
    }

    registerMouse()
    refreshScene()
    initSession()    

</script>
   
</body>